package com.lucene;
/*
 * @authon:周洋帆
 * @description:根据传入关键词，搜索网易公开课lucene索引。返回结果。
 * @param： 
 *     result:json返回结果，列表中包含返回的一系列符合结果的公开课视频链接和标题。
 *     filePath:网易公开课索引存储位置。
 * @see
 *     search方法：根据关键词从已经建好的lucene索引中获取结果，并以合适的格式返回。
 */
import com.video.*;
import java.util.*;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.queryparser.classic.ParseException;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;
import org.wltea.analyzer.lucene.IKAnalyzer;

import java.io.*;
public class OpenClasses {
    public List<ResultSet> search(String keyWord){
    	List<ResultSet> result=new ArrayList<ResultSet>();
    	String filePath="d:/MySQL/index/titleIndex";
    	File f=new File(filePath);
		int numTotalHits=0;
		try {
			IndexSearcher searcher=new IndexSearcher(DirectoryReader.open(FSDirectory.open(f)));			
			Analyzer analyzer = new IKAnalyzer();
			QueryParser parser = new QueryParser(Version.LUCENE_4_10_0, "title", analyzer);		
			Query query=parser.parse(keyWord);
			TopDocs hits=searcher.search(query,4);
			numTotalHits = hits.totalHits;
			if(numTotalHits==0){
				return null;
			}
			for(ScoreDoc doc:hits.scoreDocs){
				ResultSet rs=new ResultSet();
				Document d=searcher.doc(doc.doc);
//				System.out.println(d.get("title")+"\t"+d.get("classid"));
				rs.setTitle(d.get("title"));
				rs.setVideoUrl(d.get("url"));
				String picPath="/book/pics/"+d.get("classid")+".jpg";
				rs.setPicUrl(picPath);
				result.add(rs);
			}
			
		} catch (IOException | ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	return result;
    }
}
